#include "StdAfx.h"
#include "DBAssist.h"

CDBAssist::CDBAssist(void)
{
}

CDBAssist::~CDBAssist(void)
{
	//m_Rs.Close();
	//m_Database.Close();	
}
BOOL CDBAssist::ConnectDB(MYSQLSERVERINFO *mysqlserverinfo)
{
	m_mysqlserverinfo = mysqlserverinfo;
	m_mysqlserverinfo->dbuserid = "root";
	m_mysqlserverinfo->dbpassword = "12345";
	m_mysqlserverinfo->dbname = "member";
	mysql_init(&m_mysql);
	if (!mysql_real_connect(
		&m_mysql,m_mysqlserverinfo->dbip,
		m_mysqlserverinfo->dbuserid, 
		m_mysqlserverinfo->dbpassword, 
		m_mysqlserverinfo->dbname,
		m_mysqlserverinfo->dbport,
		NULL,
		0)		)
	{
		return FALSE;
	}
	else
	{
		SetDefault();
		m_mysqlserverinfo->islinked = TRUE;
		return TRUE;
	}
}
void CDBAssist::SetDefault()
{
	CString str = L"SET character_set_client='gbk'";
	Execute(str);
	str = L"SET character_set_connection='gbk'";
	Execute(str);
	str = L"SET character_set_results='gbk'";
	Execute(str);
}
BOOL CDBAssist::CloseDB()
{
	mysql_close(&m_mysql);
	return TRUE;
}
std::vector<Member>* CDBAssist::Query(CString sqlstr)
{
	char *query= new char[sqlstr.GetLength()+1];
	int i;
	for(i=0;i<sqlstr.GetLength();i++)
	{
		query[i]=(char)sqlstr.GetAt(i);
	}
	query[i]='\0';
	std::vector<Member>* membervector = new std::vector<Member>();
	int t = mysql_real_query(&m_mysql,query,(unsigned int) strlen(query));
	if (t)
	{
		return NULL;
	}	
	m_res = mysql_store_result(&m_mysql); 
	while(m_row = mysql_fetch_row(m_res))
	{		
		Member member;
		member.id = m_row[0];
		member.password = m_row[1];
		membervector->push_back(member);
	}
	return membervector;
}
BOOL CDBAssist::Execute(CString sqlstr)
{
	char *query= new char[sqlstr.GetLength()+1];
	int i;
	for(i=0;i<sqlstr.GetLength();i++)
	{
		query[i]=(char)sqlstr.GetAt(i);
	}
	query[i]='\0';

	int t = mysql_real_query(&m_mysql,query,(unsigned int) strlen(query));
	delete []query;
	return (t==0 ? FALSE : TRUE);
}
